<template>
  <el-dialog
    ref="formDlg"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="85%"
    append-to-body
    @close="closeDialog"
  >
    <template slot="title">
      <div>
        <span v-text="spaceName" />
        <el-checkbox v-model="childrenCheck" label="选择方案" border @change="changeCheck" />
      </div>
    </template>
    <div class="table-main">
      <div class="table-left">
        <table-box
          ref="refTable"
          :table-config="tableConfig"
          :other-filters="otherFilters"
          table-row-key="id"
          :show-page="false"
          :table-height="400"
          :selected-arry.sync="tableSelected"
          :table-row-class-name="tableRowClassName"
          @row-click="select"
          @selection-change="selectionChangeHandle"
          @data-change="tableDataChange"
        >
          <el-table-column fixed="left" type="selection" reserve-selection :selectable="canSelect" />
        </table-box>
      </div>
      <div v-if="false" class="table-right">
        <div class="qup-title-box"><span class="border" /><span>已选方案</span></div>
        <div class="table-list-box">
          <el-table
            style="width: 100%"
            :data="selectedRows"
            :height="500"
            header-row-class-name="table-list-header"
            highlight-current-row
            border
          >
            <el-table-column type="index" label="序号" />
            <el-table-column show-overflow-tooltip min-width="105" prop="styleName" label="所属专区" />
            <el-table-column show-overflow-tooltip prop="seriesName" label="产品系列" />
            <!-- <el-table-column show-overflow-tooltip prop="designApplyArea" label="设计申请面积" />
            <el-table-column show-overflow-tooltip prop="checked" label="配套" /> -->

            <el-table-column show-overflow-tooltip min-width="100" prop="spaceName" label="所属空间" />
            <el-table-column show-overflow-tooltip prop="assortCustomizedSeriesName" label="配套定制系列" />
            <el-table-column show-overflow-tooltip prop="assortCupboardSeriesName" label="配套橱柜系列" />

            <el-table-column show-overflow-tooltip prop="adviceCityLevel" label="建议城市级别">
              <template slot-scope="scope">{{ formaterData(adviceCityLevelOptions, scope.row.adviceCityLevel) }}</template>
            </el-table-column>
            <el-table-column prop="isMustUp" label="是否必上">
              <template slot-scope="scope">{{ scope.row.isMustUp===1?'是':'否' }}</template>
            </el-table-column>
            <el-table-column show-overflow-tooltip prop="adviceSampleMinArea" label="建议上样最低面积" />
            <el-table-column show-overflow-tooltip prop="seriesDesc" label="系列说明" />
            <el-table-column label="操作" width="80" fixed="right">
              <template v-slot="{row}">
                <el-button class="my-button" type="text" size="mini" @click="currentChange(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <div slot="footer">
      <el-button size="mini" @click="closeDialog">取消</el-button>
      <el-button size="mini" type="primary" @click="handleSure">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getPruductAllData } from '@/api/shopDesign'
import { formaterData, deepClone } from '@/utils'
import { sortArr } from '@/utils/mergeArr'

import { getDictByPatchType } from '@/api/dataDict'
export default {
  name: 'AddProgram',
  components: {},
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    checked: {
      type: Boolean,
      default: false
    },
    initData: {
      type: Array,
      default: () => []
    },
    programId: {
      type: String,
      default: ''
    },
    spaceName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      sortArr,
      formaterData,
      isFirst: true,
      allTableData: [],
      mustList: [],
      childrenCheck: false,
      otherFilters: [{ id: 'enable', property: 'enable', value: '1', operator: '=' }, { id: 'dr', property: 'dr', value: '0', operator: '=' }],

      // 待选方案
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configProgramProductSeries/page`,
        onlySearchBar: true,
        tabIndex: 0,
        sort: 'isMustUp',
        order: 'desc',
        pageFlag: false,
        setting: [

          {
            prop: 'styleName',
            label: '所属专区',
            minWidth: '120'
          },

          {
            prop: 'adviceArea',
            label: '建议面积',
            minWidth: '120'
          },
          {
            prop: 'seriesName',
            label: '产品系列',
            minWidth: '120'
          },
          {
            prop: 'assortCustomizedSeriesName',
            label: '配套定制系列',
            minWidth: '120'
          },
          {
            prop: 'assortCupboardSeriesName',
            label: '配套橱柜系列',
            minWidth: '120'
          },
          {
            prop: 'seriesDesc',
            label: '系列说明',
            minWidth: '120'
          },
          {
            prop: 'isMustUp',
            label: '是否必上',
            type: 'select',
            minWidth: '120',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BOOLEANS'
            }
          },
          {
            prop: 'enable',
            label: '启用状态',
            minWidth: '120',
            render: function(createElement, rows) {
              if (rows.enable === 1 || rows.enable === 0) {
                return (<div>
                  <div>
                    {rows.enable === 1 ? '启用' : '停用' }</div>
                </div>
                )
              }
              return ''
            }
          }
        ],
        btnList: !this.isProduction ? [] : null
      },
      adviceCityLevelOptions: [],
      selectedRows: [], // 多选行
      cancelSelectedRows: [], // 已取消选择的行
      tableSelected: [], // 单选行
      initSelecteds: []
    }
  },
  watch: {
    visible(val, oldVal) {
      if (!val) {
        this.tableSelected = []
        this.selectedRows = []
      }
      if (!oldVal && val) {
        this.$refs.refTable.initTableData()
      }
    },
    allTableData: {
      handler(val, oldVal) {
        this.$nextTick(() => {
          this.reSetTableSelection()
        })
      },
      deep: true
    },
    selectedRows: {
      handler(v) {
        if (v.length > 0) {
          this.childrenCheck = true
          this.allTableData.forEach((row, keyIndex) => {
            const index = this.mustList.findIndex(item => item.id === row.id)
            if (index > -1) this.$refs.refTable.toggleRowSelection(row, true)
          })
        } else this.childrenCheck = false
      }
    }
  },
  async  created() {
    this.isFirst = false
    getPruductAllData(this.programId).then(res => {
      if (res.success === 1) this.mustList = res.data.records.filter(el => el.isMustUp)
    })
    this.otherFilters.push({ 'property': 'configProgramProductId', 'value': this.programId, 'operator': '=', 'id': 'configProgramProductId' })
    this.initSelecteds = deepClone(this.initData)
    this.childrenCheck = this.checked
    const { CITY_LEVEL } = await getDictByPatchType(['CITY_LEVEL'])
    this.adviceCityLevelOptions = CITY_LEVEL
  },
  methods: {
    select() {
      // if (this.childrenCheck) this.changeCheck(true)
    },
    canSelect(row, index) {
      if (this.childrenCheck && row.isMustUp) return false
      else return true
    },
    currentChange(row) {
      if (row.isMustUp) {
        this.$confirm('当前数据为必上，取消选择将会取消方案的选择, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.childrenCheck = false
          this.selectedRows.forEach(el => {
            this.delSelectedRow(el)
          })
        })
      } else {
        this.delSelectedRow(row)
      }
    },
    changeCheck(data) {
      this.childrenCheck = data
      if (!data) {
        this.selectedRows.forEach(el => {
          this.delSelectedRow(el)
        })
        this.initSelecteds.forEach(el => {
          this.delSelectedRow(el)
        })
        this.selectedRows = []
        this.initSelecteds = []
      } else {
        if (this.selectedRows.length === 0) {
          this.selectedRows = deepClone(this.mustList)
          // this.initSelecteds = deepClone(this.mustList)
        }
      }
    },
    closeDialog() {
      this.$refs.refTable.clearSelection()
      this.selectedRows = [] // 表格多选行
      this.tableSelected = [] // 表格单选行
      this.$emit('update:visible', false)
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.selectedRows.filter(item => item.id === row.id)
      return filterArr.length > 0 ? 'selected-highlight' : ''
    },
    tableDataChange(res) {
      this.allTableData = (res && res.data && res.data.records) || []
      this.allTableData.forEach((row, keyIndex) => {
        const tempArr = this.initSelecteds.filter((v, index) => v.id === row.id)
        if (tempArr.length > 0) {
          this.$set(row, 'checked', tempArr[0].checked)
          this.$set(row, 'actualReportArea', tempArr[0].actualReportArea)
          this.$set(row, 'chooseCustomizedSeriesName', tempArr[0].chooseCustomizedSeriesName)
          this.$set(row, 'chooseCupboardSeriesName', tempArr[0].chooseCupboardSeriesName)
          const newRow = { ...row, ...{ keyIndex, checked: tempArr[0].checked }}
          const rowIndex = this.selectedRows.findIndex(v => v.id === row.id)
          if (rowIndex === -1) {
            this.selectedRows.push(newRow)
            this.$refs.refTable.toggleRowSelection(newRow, true)
          } else {
            this.$set(this.selectedRows, rowIndex, newRow)
          }
        } else {
          const delRow = { ...row, ...{ keyIndex }}
          this.$refs.refTable.toggleRowSelection(delRow, false)
        }
      })
    },
    // 重置当前页已选中数据的复选状态
    reSetTableSelection() {
      // 判断当前表数据中是存在已取消选中的数据，若存在，则取消表格数据的选中
      const delIds = []
      this.cancelSelectedRows.forEach(row => {
        const tmp = this.allTableData.filter(item => item.id === row.id)
        if (tmp.length > 0) { // 在当前页表格数据中则取消选中
          this.$refs.refTable.toggleRowSelection(tmp[0], false)
          delIds.push(row.id)
        }
      })
      delIds.forEach(id => {
        const index = this.cancelSelectedRows.findIndex(row => row.id === id)
        this.cancelSelectedRows.splice(index, 1)

        if (this.initSelecteds && this.initSelecteds.length) {
          const indexSelect = this.initSelecteds.findIndex(row => row.id === id)
          if (indexSelect > -1) {
            this.initSelecteds.splice(indexSelect, 1)
          }
        }
      })
    },
    selectionChangeHandle(rows) {
      const obj = {}
      // 去重
      rows = rows.reduce(function(item, next) {
        obj[next.id] ? '' : obj[next.id] = true && item.push(next)
        return item
      }, [])
      this.selectedRows = rows
    },
    // 移除已选择方案
    delSelectedRow(row) {
      const tmp = this.allTableData.filter(item => row.id === item.id)
      if (tmp.length > 0) { // 在当前页表格数据中则取消选中
        this.$refs.refTable.toggleRowSelection(tmp[0], false)
      } else { // 未在当前表格数据中，则加入到取消选中的数据集中，并从已选组织表中删除
        this.cancelSelectedRows.push(row)
        const index = this.selectedRows.indexOf(row)
        this.selectedRows.splice(index, 1)
      }
    },
    handleSure() {
      const rows = this.selectedRows.map(v => {
        this.$set(v, 'customizedSeriesList', (v.assortCustomizedSeriesName && v.assortCustomizedSeriesName.split(',')) || [])
        this.$set(v, 'cupboardSeriesList', (v.assortCupboardSeriesName && v.assortCupboardSeriesName.split(',')) || [])
        this.$set(v, 'chooseCustomizedSeriesName', [])
        this.$set(v, 'chooseCupboardSeriesName', [])

        return v
      })
      const datas = this.sortArr(rows, 'styleCode').flat(Infinity)
      this.$emit('change', datas, this.childrenCheck)
      this.closeDialog()
    }
  }
}
</script>

<style lang='scss' scoped>
.goods_img {
  margin: 5px;
  max-width: 100%;
  max-height: 50px;
  -o-object-fit: cover;
  object-fit: cover;
  vertical-align: middle;
}
  .table-main{
    width: 100%;
    display: flex;
    .table-left{
      width: 50%;
      box-sizing: border-box;
      /deep/ .btn-box{
        display: none;
      }
    }
    .table-right{
      width:50%;
    }
    .table-left{
      flex:1;
      padding-right: 10px;
    }
    .table-right{
      padding-left: 10px;
      .qup-title-box{
        line-height: 28px;
        height: 28px;
        margin-bottom: 10px;
      }
      // padding-top: 38px;
      .table-list-box{
        margin-top: 0;
      }
    }
  }
  /deep/ .pagination-info{
    display: none
  }
</style>
